import fs from "fs-extra";
import fg from "fast-glob";
import path from "path";
import { CmdOption } from "../typings/index.js";
import { UnityHelper } from "./UnityHelper.js";
import { PrefabParser } from "../unity/PrefabParser.js";

interface YAMLSection {
    start: number
    end: number
    fileID: string
    remove?: boolean
}

export class ScriptStriper {
    public async removeScript(option: CmdOption, scriptCS: string): Promise<void> {
        const scriptGUID = await UnityHelper.readGUID(scriptCS + '.meta');

        const prefabRoot = path.join(option.projectRoot, 'Assets');
        const prefabs = await fg('**/*.prefab', { cwd: prefabRoot });
        let modifiedCnt = 0;
        for (const prefab of prefabs) {
            const f = path.join(prefabRoot, prefab);
            const content = await fs.readFile(f, 'utf-8');
            const lines = content.split(/\r?\n/);

            let section: YAMLSection = { start: 0, end: 0, fileID: '' };
            const sections: YAMLSection[] = [section];
            for (let i = 0, len = lines.length; i < len; i++) {
                const mch = lines[i].match(PrefabParser.SectionHeader);
                if (mch != null) {
                    section = { start: i, end: 0, fileID: mch[2] };
                    sections.push(section);
                } else {
                    section.end = i;
                    if (lines[i].match(new RegExp(`m_Script: \\{fileID: \\d+, guid: ${scriptGUID}, type: 3\\}`))) {
                        section.remove = true;
                    }
                }
            }
            let modified = false;
            for (let i = sections.length - 1; i >= 0; i--) {
                const section = sections[i];
                if (section.remove) {
                    modified = true;
                    lines.splice(section.start, section.end - section.start + 1);
                }
            }
            for (const section of sections) {
                if (section.remove) {
                    for (let i = lines.length - 1; i >= 0; i--) {
                        if (lines[i] == `  - component: {fileID: ${section.fileID}}`) {
                            lines.splice(i, 1);
                        }
                    }
                }
            }
            if (modified) {
                modifiedCnt++;
                await fs.writeFile(f, lines.join('\n'), 'utf-8');
            }
        }
        console.log(`${modifiedCnt} prefab modified`);
    }
}
